package com.ddwl.wallet.repository.impl;

import com.ddwl.common.constant.BaseEnum;
import com.ddwl.common.constant.WalletEnum;
import com.ddwl.wallet.dao.model.Coupon;
import com.ddwl.wallet.repository.CouponRepositoryAdvance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class CouponRepositoryImpl implements CouponRepositoryAdvance {

    @Autowired
    private MongoTemplate template;

    /**
     * 用户可以领取满减券和购买代金券
     *
     * @param shopId
     * @return
     */
    @Override
    public List<Coupon> findByShopId(String shopId) {
        Date now = new Date();
        Criteria criteria = Criteria.where("type").in(Arrays.asList(WalletEnum.CouponType.REDUCTION.getCode(), WalletEnum.CouponType.VOUCHER.getCode()))
                .orOperator(Criteria.where("shopIds").is(shopId), Criteria.where("shopIds").exists(false))
                .and("dflag").is(BaseEnum.DflagEnum.NOT_DELETE.getCode())
                .and("enable").is(BaseEnum.StatusEnum.ENABLE.getCode())
                .and("beginDate").lte(now).and("endDate").gte(now);
        return template.find(Query.query(criteria), Coupon.class);
    }

    @Override
    public List<Coupon> findByItem(List<String> itemIds) {
        Criteria criteria = Criteria.where("itemId")
                .in(itemIds).and("type").is(WalletEnum.CouponType.EXCHANGE.getCode())
                .and("dflag").is(BaseEnum.DflagEnum.NOT_DELETE.getCode())
                .and("enable").is(BaseEnum.StatusEnum.ENABLE.getCode());
        return template.find(Query.query(criteria), Coupon.class);
    }

    @Override
    public List<Coupon> findByAmount(BigDecimal amount) {
        Criteria criteria = Criteria.where("minAmount")
                .lte(amount).and("type").is(WalletEnum.CouponType.REDUCTION.getCode())
                .and("dflag").is(BaseEnum.DflagEnum.NOT_DELETE.getCode())
                .and("enable").is(BaseEnum.StatusEnum.ENABLE.getCode());
        return template.find(Query.query(criteria), Coupon.class);
    }

    @Override
    public List<Coupon> findByVoucher() {
        Criteria criteria = Criteria.where("type").is(WalletEnum.CouponType.VOUCHER.getCode())
                .and("dflag").is(BaseEnum.DflagEnum.NOT_DELETE.getCode())
                .and("enable").is(BaseEnum.StatusEnum.ENABLE.getCode());
        return template.find(Query.query(criteria), Coupon.class);
    }
}
